const sqllite3 = require('sqlite3');

class DataBase {

    constructor(dbFilePath){
        this.db = new sqllite3.Database(dbFilePath, (err) => {
            if(err){
                console.log('Could not connect to database', err)
            }else{
                console.log('Connected to database')
            }
        });
    }

    run(sql, params){
        return new Promise((resolve, reject) => {
            console.log('running sql: ' + sql);
            this.db.run(sql, params, function(err){
                if(err){
                    console.log('sql running error: ' + sql);
                    console.log(err);
                    reject(err);
                }else{
                    resolve(this.lastID);
                }
            });
        });
    }

    get(sql, params=[]){
        return new Promise((resolve, reject) => {
            this.db.get(sql, params, (err, row) => {
                if(err){
                    console.log('Error running sql: ' + sql);
                    console.log(err);
                    reject(err);
                }else{
                    resolve(row);
                }
            });
        });
    }

    all(sql, params=[]){
        return new Promise((resolve, reject) => {
            this.db.all(sql, params, (err, rows) => {
                if(err){
                    console.log('Error running sql: ' + sql);
                    console.log(err);
                    reject(err);
                }else{
                    resolve(rows);
                }
            });
        });
    }
}

const db = new DataBase('./database.sqllite3');

module.exports = db;